import { Row } from 'antd';
import { LockOutlined, UserOutlined, MailOutlined } from '@ant-design/icons';
import { Button, Form, Flex, Modal } from 'antd';
import { success, error } from '../../utils/Notification'
import { useState } from 'react';
import CardHeader from '../../components/Login/CardHeader';
import CardTag from '../../components/Login/CardTag';
import { CardFormInput, CardFormValid, CardFormAgree, CardFormForgetPassword } from '../../components/Login/CardFormItem';
import { EmailLogin, UsernameLogin, GetRegisterCode, Register, ForgetPassword } from '../../api/Login';
import { useNavigate } from "react-router-dom";
import LoginStore from '../../store/Login/index';
const Login = () => {

  const {token,setToken,userInfo,setUserInfo} = LoginStore();



  const navigate = useNavigate();//路由实例

  const [validCodeSecond, setValidCodeSecond] = useState(100);

  const [isClickValid,setIsClickValid] = useState(false);//true:按了,false:没按

  const [loginForm] = Form.useForm();//登录表单
  //获取验证码
  const GetValidCode = (value) => {

    if (isClickValid) {
      error('重复点击警告', '重复点击将会导致消耗服务器的资源,我们将追究您的法律责任,或者我们会直接过去弄死你');
      return;
    }else{
      setIsClickValid(true);
      setInterval(() => {
        setValidCodeSecond((prev)=>{
          if(prev>0){
            return prev-1;
          }else{
            setIsClickValid(false);
            return 100;
          }
        }); 
      }, 1000);
    }

    console.log(value);//验证码

    let email = loginForm.getFieldValue('email');//163邮箱

    console.log({ email: email });//实体参数

    GetRegisterCode({ email: email }).then(res => {
      if (res.data.code === 200) {
        success(res.data.msg, '验证码已发送至邮箱');
      } else {
        error('验证码发送错误', res.data.msg);
      }
    })
  }
  //提交表单
  const onFinish = (values) => {
    if (formStatus === 1) {
      console.log('用户名登录');
      UsernameLogin(values).then(res => {
        if (res.data.code === 200) {
          success(res.data.msg, '欢迎回来');
          navigate('/');
          console.log(res.data.data);
          setToken(res.data.data.token);
          setUserInfo(res.data.data.user);
        } else {
          error('登录失败', res.data.msg);
        }
      })
    } else if (formStatus === 2) {
      console.log('邮箱登录');
      EmailLogin(values).then(res => {
        if (res.data.code === 200) {
          success(res.data.msg, '欢迎回来');
          navigate('/');
          console.log(res.data);
        } else {
          error('登录失败', res.data.msg);
        }
      })
    } else if (formStatus === 3) {
      //获取表单中的所有值
      if(!loginForm.getFieldValue('agree')){
        error('请先同意低质文章发布协议', '请先阅读并同意协议');
      }
      
      
      console.log('注册');
      Register({
        username: loginForm.getFieldValue('username'),
        password: loginForm.getFieldValue('password'),
        email: loginForm.getFieldValue('email'),
        validCode: loginForm.getFieldValue('validcode')
      }).then((result) => {
        console.log(result);
        if (result.data.code === 200) {
          success(result.data.msg, result.data.data);
          setFormStatus(1);
        } else {
          error('注册失败', result.data.msg);
        }
      })
    } else if (formStatus === 4) {
      console.log('忘记密码');
      ForgetPassword({
        username: loginForm.getFieldValue('username'),
        password: loginForm.getFieldValue('password'),
        email: loginForm.getFieldValue('email'),
        validCode: loginForm.getFieldValue('validcode')
      }).then(result => {
        if (result.data.code === 200) {
          success(result.data.msg, result.data.data);
          setFormStatus(1);
        } else {
          error('找回密码失败', result.data.msg);
        }
      })
    }
  };
  //登录标签结构样式函数
  const Tags = () => {
    if (formStatus === 1 || formStatus === 2) {
      return (
        <div style={{ widows: '100%' }} className='my-4'>
          <Row>
            <CardTag name="用户名" showFlag={formStatus === 1} click={() => setFormStatus(1)}></CardTag>
            <CardTag name="邮箱" showFlag={formStatus === 2} click={() => setFormStatus(2)}></CardTag>
          </Row>
        </div>
      );
    }
  }
  const [formStatus, setFormStatus] = useState(1);//1:用户名登录,2:邮箱登录,3:注册,4:忘记密码
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <>
      <Modal
        title="发布低质文章处理"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>敢他妈的发垃圾文章的话</p>
        <p>我陈浩南他妈的带着洪兴的双花红棍过来砍死你丫的!</p>
      </Modal>
      <div style={{ width: "100vw", height: "100vh", display: "flex", justifyContent: "center", alignItems: "center" }}>
        <div style={{ width: "500px", border: "1px solid #ccc", padding: "20px", borderRadius: "20px" }}>
          <CardHeader></CardHeader>
          <Tags></Tags>
          <Form
            form={loginForm}
            name="login"
            initialValues={{ agree: true }}
            onFinish={onFinish}
            style={{ marginTop: "20px" }}
          >
            <CardFormInput
              showFlag={[1, 3, 4].includes(formStatus)}
              name={'username'}
              require={true}
              message={'Please input your Username!'}
              prefix={<UserOutlined />}
              placeholder={'Username'}
            />
            <CardFormInput
              showFlag={[2, 3, 4].includes(formStatus)}
              name={'email'}
              require={true}
              message={'Please input your Email!'}
              prefix={<MailOutlined />}
              placeholder={'Email'}
            />
            <CardFormInput
              showFlag={[1, 2, 3, 4].includes(formStatus)}
              name={'password'}
              require={true}
              message={'Please input your Password!'}
              prefix={<LockOutlined />}
              placeholder={'Password'}
            />
            <CardFormValid
              showFlag={[3, 4].includes(formStatus)}
              name={'validcode'}
              rules={[{ required: true, message: 'Please input your Captcha!' }]}
              placeholder={'Validate Code'}
              enterButton={!isClickValid?'点击获取163邮箱验证码or Fucking QQ Email':validCodeSecond}
              search={GetValidCode}
            />
            <CardFormAgree status={formStatus} click={() => { showModal() }} />
            <Form.Item>
              <Button block type="primary" htmlType="submit">
                submit
              </Button>
              <Flex justify="space-between" align="center" className='my-4'>
                <p>{formStatus === 3 ? '已有账号' : '没有账号'}?前去<a onClick={() => setFormStatus(formStatus === 3 ? 1 : 3)}>{formStatus === 3 ? '登录' : '注册'}!</a></p>
                <CardFormForgetPassword showflag={[1, 2].includes(formStatus)} click={() => setFormStatus(4)} />
              </Flex>
            </Form.Item>
          </Form>
        </div>
      </div>
    </>

  );
};
export default Login;